#pragma once
#include <string>
#include <unordered_map>
#include <sstream>
#include <vector>
#include <memory>
#include <random>
#include <chrono>
#include <iomanip>
#include <regex>
#include <nlohmann/json.hpp>
#include "Kv_Foundation.hpp"
#include "Kv_more.hpp"
#include "Kv_cluster.hpp"

namespace Business_Ctrl {
    using namespace std;
    using namespace Redis_Foundation_Model;
    using namespace Redis_Cluster_Model;
    using json = nlohmann::json;

    // 序列化格式类型
    enum class SerializeFormat {
        JSON = 0,
        PROTOBUF = 1,
        MESSAGEPACK = 2
    };

    // 银行业务数据结构
    struct BankAccount {
        string 账户号;
        string 用户ID;
        string 账户类型 = "储蓄账户";
        double 余额 = 0.0;
        string 币种 = "CNY";
        string 状态 = "正常";
        string 开户日期;
        double 信用额度 = 0.0;
        double 可用余额 = 0.0;
        
        string serialize() const {
            json j;
            j["账户号"] = 账户号;
            j["用户ID"] = 用户ID;
            j["账户类型"] = 账户类型;
            j["余额"] = 余额;
            j["币种"] = 币种;
            j["状态"] = 状态;
            j["开户日期"] = 开户日期;
            j["信用额度"] = 信用额度;
            j["可用余额"] = 可用余额;
            return j.dump();
        }
        
        static BankAccount deserialize(const string& data) {
            BankAccount account;
            try {
                json j = json::parse(data);
                account.账户号 = j.value("账户号", "");
                account.用户ID = j.value("用户ID", "");
                account.账户类型 = j.value("账户类型", "储蓄账户");
                account.余额 = j.value("余额", 0.0);
                account.币种 = j.value("币种", "CNY");
                account.状态 = j.value("状态", "正常");
                account.开户日期 = j.value("开户日期", "");
                account.信用额度 = j.value("信用额度", 0.0);
                account.可用余额 = j.value("可用余额", 0.0);
            } catch (...) {
                // 静默处理反序列化错误
            }
            return account;
        }
    };

    struct UserInfo {
        string 用户ID;
        string 用户名;
        string 姓名;
        string 身份证号;
        string 手机号;
        string 邮箱;
        string 注册日期;
        string 最后登录;
        string 状态 = "正常";
        
        string serialize() const {
            json j;
            j["用户ID"] = 用户ID;
            j["用户名"] = 用户名;
            j["姓名"] = 姓名;
            j["身份证号"] = 身份证号;
            j["手机号"] = 手机号;
            j["邮箱"] = 邮箱;
            j["注册日期"] = 注册日期;
            j["最后登录"] = 最后登录;
            j["状态"] = 状态;
            return j.dump();
        }
        
        static UserInfo deserialize(const string& data) {
            UserInfo user;
            try {
                json j = json::parse(data);
                user.用户ID = j.value("用户ID", "");
                user.用户名 = j.value("用户名", "");
                user.姓名 = j.value("姓名", "");
                user.身份证号 = j.value("身份证号", "");
                user.手机号 = j.value("手机号", "");
                user.邮箱 = j.value("邮箱", "");
                user.注册日期 = j.value("注册日期", "");
                user.最后登录 = j.value("最后登录", "");
                user.状态 = j.value("状态", "正常");
            } catch (...) {
                // 静默处理反序列化错误
            }
            return user;
        }
    };

    struct Transaction {
        string 交易ID;
        string 账户号;
        string 交易类型;
        double 金额;
        string 币种 = "CNY";
        string 时间戳;
        string 描述;
        string 对方账户;
        string 状态 = "成功";
        
        string serialize() const {
            json j;
            j["交易ID"] = 交易ID;
            j["账户号"] = 账户号;
            j["交易类型"] = 交易类型;
            j["金额"] = 金额;
            j["币种"] = 币种;
            j["时间戳"] = 时间戳;
            j["描述"] = 描述;
            j["对方账户"] = 对方账户;
            j["状态"] = 状态;
            return j.dump();
        }
        
        static Transaction deserialize(const string& data) {
            Transaction trans;
            try {
                json j = json::parse(data);
                trans.交易ID = j.value("交易ID", "");
                trans.账户号 = j.value("账户号", "");
                trans.交易类型 = j.value("交易类型", "");
                trans.金额 = j.value("金额", 0.0);
                trans.币种 = j.value("币种", "CNY");
                trans.时间戳 = j.value("时间戳", "");
                trans.描述 = j.value("描述", "");
                trans.对方账户 = j.value("对方账户", "");
                trans.状态 = j.value("状态", "成功");
            } catch (...) {
                // 静默处理反序列化错误
            }
            return trans;
        }
    };

    // 业务操作结果
    struct BizResult {
        bool 成功;
        string 数据;
        string 错误信息;
        int 状态码;
        
        BizResult(bool s = false, const string& d = "", const string& err = "", int c = 0) 
            : 成功(s), 数据(d), 错误信息(err), 状态码(c) {}
        
        string serialize() const {
            json j;
            j["成功"] = 成功;
            j["状态码"] = 状态码;
            j["数据"] = 数据;
            j["错误信息"] = 错误信息;
            return j.dump();
        }
        
        static BizResult deserialize(const string& data) {
            try {
                json j = json::parse(data);
                return BizResult(
                    j.value("成功", false),
                    j.value("数据", ""),
                    j.value("错误信息", ""),
                    j.value("状态码", 0)
                );
            } catch (...) {
                return BizResult(false, "", "反序列化失败", 500);
            }
        }
    };

    // 验证工具类
    class Validator {
    public:
        static bool validateUsername(const string& username) {
            regex pattern("^[a-zA-Z0-9]{4,20}$");
            return regex_match(username, pattern);
        }
        
        static bool validateIdCard(const string& id_card) {
            regex pattern("^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$");
            return regex_match(id_card, pattern);
        }
        
        static bool validatePhone(const string& phone) {
            regex pattern("^1[3-9]\\d{9}$");
            return regex_match(phone, pattern);
        }
        
        static bool validateAmount(double amount) {
            return amount > 0 && amount <= 1000000;
        }
        
        static bool validateEmail(const string& email) {
            regex pattern(R"(^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$)");
            return regex_match(email, pattern);
        }
    };

    // 多级键值业务控制器
    class MultiLevelController {
    private:
        shared_ptr<KvMore> _kv_more;
        shared_ptr<Redis_Cluster_Model::KvCluster> _kv_cluster;
        
        // 命名空间
        const string 会话空间 = "bank:session";
        const string 账户空间 = "bank:account";
        const string 用户空间 = "bank:users";
        const string 交易空间 = "bank:transactions";
        const string 风控空间 = "bank:risk";
        const string 锁空间 = "bank:lock";
        const string 统计空间 = "bank:stats";
        
        // 生成唯一ID
        string generateId(const string& prefix) {
            auto now = chrono::system_clock::now();
            auto timestamp = chrono::duration_cast<chrono::milliseconds>(now.time_since_epoch()).count();
            random_device rd;
            mt19937 gen(rd());
            uniform_int_distribution<> dis(1000, 9999);
            return prefix + to_string(timestamp) + to_string(dis(gen));
        }
        
        // 获取当前时间字符串
        string getCurrentTime() {
            auto now = chrono::system_clock::now();
            auto time_t = chrono::system_clock::to_time_t(now);
            stringstream ss;
            ss << put_time(localtime(&time_t), "%Y-%m-%d %H:%M:%S");
            return ss.str();
        }

        // 记录交易
        void recordTransaction(const string& account_no, const string& trans_type, 
                              double amount, const string& description, const string& counterparty) {
            Transaction trans;
            trans.交易ID = generateId("TRANS");
            trans.账户号 = account_no;
            trans.交易类型 = trans_type;
            trans.金额 = amount;
            trans.时间戳 = getCurrentTime();
            trans.描述 = description;
            trans.对方账户 = counterparty;
            
            _kv_more->set(交易空间, trans.交易ID, trans.serialize());
            
            string trans_list_key = "transactions:" + account_no;
            _kv_more->lpush(交易空间, trans_list_key, trans.交易ID);
            
            // 保持最近100条交易记录
            if (_kv_more->llen(交易空间, trans_list_key) > 100) {
                auto popped = _kv_more->rpop<std::string>(交易空间, trans_list_key);
            }
            
            // 更新统计信息
            updateStatistics(trans_type, amount);
        }
        
        // 更新统计信息
        void updateStatistics(const string& trans_type, double amount) {
            string today = getCurrentTime().substr(0, 10); // YYYY-MM-DD
            _kv_more->incrbyfloat(统计空间, "日交易总额:" + today, amount);
            _kv_more->incr(统计空间, "日交易笔数:" + today, 1);
            _kv_more->incrbyfloat(统计空间, "总交易金额", amount);
            _kv_more->incr(统计空间, "总交易笔数", 1);
        }

        // 安全的字符串转换
        double safeStod(const string& str, double default_val = 0.0) {
            try {
                return stod(str);
            } catch (...) {
                return default_val;
            }
        }

        int safeStoi(const string& str, int default_val = 0) {
            try {
                return stoi(str);
            } catch (...) {
                return default_val;
            }
        }

        // 检查唯一性约束
        bool checkUniqueConstraints(const string& username, const string& id_card, const string& phone) {
            if (_kv_more->exists(用户空间, "username:" + username)) {
                return false;
            }
            if (_kv_more->exists(用户空间, "id_card:" + id_card)) {
                return false;
            }
            if (_kv_more->exists(用户空间, "phone:" + phone)) {
                return false;
            }
            return true;
        }
        
        // 解析带引号的参数
        vector<string> parseCommandLine(const string& command_line) {
            vector<string> tokens;
            string token;
            bool in_quotes = false;
            char quote_char = 0;
            
            for (size_t i = 0; i < command_line.length(); ++i) {
                char c = command_line[i];
                
                if (in_quotes) {
                    if (c == quote_char) {
                        in_quotes = false;
                        if (!token.empty()) {
                            tokens.push_back(token);
                            token.clear();
                        }
                    } else {
                        token += c;
                    }
                } else {
                    if (c == '"' || c == '\'') {
                        in_quotes = true;
                        quote_char = c;
                    } else if (isspace(c)) {
                        if (!token.empty()) {
                            tokens.push_back(token);
                            token.clear();
                        }
                    } else {
                        token += c;
                    }
                }
    }
    
    // 处理最后一个token
    if (!token.empty()) {
        tokens.push_back(token);
    }
    
    LOG(LogLevel::DEBUG) << "Parsed " << tokens.size() << " tokens from command";
    return tokens;
}

    public:
        MultiLevelController(shared_ptr<KvMore> kv_more = nullptr, 
                           shared_ptr<Redis_Cluster_Model::KvCluster> cluster = nullptr)
            : _kv_more(kv_more), _kv_cluster(cluster) {
            
            if (!_kv_more) {
                auto redis_client = Redis_Foundation_Model::Redis_Client::GetInstance();
                _kv_more = make_shared<KvMore>(redis_client, "bank");
            }
        }

        // ==================== 会话管理 ====================
        BizResult 创建会话(const string& user_id, int ttl_seconds = 3600) {
            try {
                if (user_id.empty()) {
                    return BizResult(false, "", "用户ID不能为空", 400);
                }

                string session_id = generateId("SESS");
                json session_data;
                session_data["用户ID"] = user_id;
                session_data["创建时间"] = getCurrentTime();
                session_data["过期时间"] = ttl_seconds;
                
                if (_kv_cluster) {
                    _kv_cluster->setex(session_id, ttl_seconds, session_data.dump());
                } else {
                    _kv_more->setex(会话空间, session_id, ttl_seconds, session_data.dump());
                }
                
                return BizResult(true, session_id, "会话创建成功", 200);
            } catch (const exception& e) {
                return BizResult(false, "", "创建会话错误", 500);
            }
        }

        BizResult 获取会话(const string& session_id) {
            try {
                if (session_id.empty()) {
                    return BizResult(false, "", "会话ID不能为空", 400);
                }

                optional<string> session_data;
                if (_kv_cluster) {
                    session_data = _kv_cluster->get<string>(session_id);
                } else {
                    session_data = _kv_more->get<string>(会话空间, session_id);
                }
                
                return session_data ? 
                    BizResult(true, *session_data, "会话获取成功", 200) :
                    BizResult(false, "", "会话不存在或已过期", 404);
            } catch (const exception& e) {
                return BizResult(false, "", "获取会话错误", 500);
            }
        }

        // ==================== 用户管理 ====================
        BizResult 注册用户(const string& username, const string& full_name, 
                              const string& id_card, const string& phone, const string& email = "") {
            try {
                // 输入验证
                if (!Validator::validateUsername(username)) {
                    return BizResult(false, "", "用户名格式无效(4-20位字母数字)", 400);
                }
                if (!Validator::validateIdCard(id_card)) {
                    return BizResult(false, "", "身份证号格式无效", 400);
                }
                if (!Validator::validatePhone(phone)) {
                    return BizResult(false, "", "手机号格式无效", 400);
                }
                if (!email.empty() && !Validator::validateEmail(email)) {
                    return BizResult(false, "", "邮箱格式无效", 400);
                }

                // 检查唯一性约束
                if (!checkUniqueConstraints(username, id_card, phone)) {
                    return BizResult(false, "", "用户名、身份证号或手机号已存在", 409);
                }
                
                string user_id = generateId("USER");
                UserInfo user;
                user.用户ID = user_id;
                user.用户名 = username;
                user.姓名 = full_name;
                user.身份证号 = id_card;
                user.手机号 = phone;
                user.邮箱 = email;
                user.注册日期 = getCurrentTime();
                
                // 存储用户信息
                _kv_more->set(用户空间, user_id, user.serialize());
                _kv_more->set(用户空间, "username:" + username, user_id);
                _kv_more->set(用户空间, "id_card:" + id_card, user_id);
                _kv_more->set(用户空间, "phone:" + phone, user_id);
                if (!email.empty()) {
                    _kv_more->set(用户空间, "email:" + email, user_id);
                }
                
                return BizResult(true, user_id, "用户注册成功", 201);
            } catch (const exception& e) {
                return BizResult(false, "", "用户注册错误", 500);
            }
        }

        BizResult 获取用户信息(const string& user_id) {
            try {
                if (user_id.empty()) {
                    return BizResult(false, "", "用户ID不能为空", 400);
                }

                auto user_data = _kv_more->get<string>(用户空间, user_id);
                return user_data ? 
                    BizResult(true, *user_data, "用户信息获取成功", 200) :
                    BizResult(false, "", "用户不存在", 404);
            } catch (const exception& e) {
                return BizResult(false, "", "获取用户信息错误", 500);
            }
        }

        // ==================== 账户管理 ====================
        BizResult 创建账户(const string& user_id, const string& account_type, double initial_deposit = 0.0) {
            try {
                // 验证用户存在
                if (!_kv_more->exists(用户空间, user_id)) {
                    return BizResult(false, "", "用户不存在", 404);
                }
                
                if (initial_deposit < 0) {
                    return BizResult(false, "", "初始存款不能为负数", 400);
                }

                string account_no = "62" + generateId("ACC").substr(4, 13);
                
                BankAccount account;
                account.账户号 = account_no;
                account.用户ID = user_id;
                account.账户类型 = account_type;
                account.余额 = initial_deposit;
                account.可用余额 = initial_deposit;
                account.开户日期 = getCurrentTime();
                account.信用额度 = (account_type == "信用账户") ? 50000.0 : 0.0;
                
                _kv_more->set(账户空间, account_no, account.serialize());
                _kv_more->set(账户空间, "user:" + user_id, account_no);
                
                if (initial_deposit > 0) {
                    recordTransaction(account_no, "存款", initial_deposit, "初始存款", "银行");
                }
                
                return BizResult(true, account_no, "账户创建成功", 201);
            } catch (const exception& e) {
                return BizResult(false, "", "创建账户错误", 500);
            }
        }

        BizResult 获取账户余额(const string& account_no) {
            try {
                auto account_data = _kv_more->get<string>(账户空间, account_no);
                if (!account_data) {
                    return BizResult(false, "", "账户不存在", 404);
                }
                
                BankAccount account = BankAccount::deserialize(*account_data);
                json result;
                result["账户号"] = account_no;
                result["余额"] = account.余额;
                result["可用余额"] = account.可用余额;
                result["币种"] = account.币种;
                
                return BizResult(true, result.dump(), "余额获取成功", 200);
            } catch (const exception& e) {
                return BizResult(false, "", "获取余额错误", 500);
            }
        }

        BizResult 获取账户详情(const string& account_no) {
            try {
                auto account_data = _kv_more->get<string>(账户空间, account_no);
                return account_data ? 
                    BizResult(true, *account_data, "账户详情获取成功", 200) :
                    BizResult(false, "", "账户不存在", 404);
            } catch (const exception& e) {
                return BizResult(false, "", "获取账户详情错误", 500);
            }
        }

        // ==================== 交易功能 ====================
        BizResult 存款(const string& account_no, double amount, const string& description = "") {
            try {
                if (amount <= 0) {
                    return BizResult(false, "", "存款金额必须大于0", 400);
                }

                auto account_data = _kv_more->get<string>(账户空间, account_no);
                if (!account_data) {
                    return BizResult(false, "", "账户不存在", 404);
                }
                
                BankAccount account = BankAccount::deserialize(*account_data);
                if (account.状态 != "正常") {
                    return BizResult(false, "", "账户状态异常", 403);
                }
                
                account.余额 += amount;
                account.可用余额 += amount;
                _kv_more->set(账户空间, account_no, account.serialize());
                
                recordTransaction(account_no, "存款", amount, 
                                description.empty() ? "存款" : description, "客户");
                
                json result;
                result["新余额"] = account.余额;
                result["可用余额"] = account.可用余额;
                
                return BizResult(true, result.dump(), "存款成功", 200);
            } catch (const exception& e) {
                return BizResult(false, "", "存款错误", 500);
            }
        }

        BizResult 取款(const string& account_no, double amount, const string& description = "") {
            try {
                if (amount <= 0) {
                    return BizResult(false, "", "取款金额必须大于0", 400);
                }

                auto account_data = _kv_more->get<string>(账户空间, account_no);
                if (!account_data) {
                    return BizResult(false, "", "账户不存在", 404);
                }
                
                BankAccount account = BankAccount::deserialize(*account_data);
                if (account.状态 != "正常") {
                    return BizResult(false, "", "账户状态异常", 403);
                }
                
                if (account.可用余额 < amount) {
                    return BizResult(false, "", "余额不足", 400);
                }
                
                account.余额 -= amount;
                account.可用余额 -= amount;
                _kv_more->set(账户空间, account_no, account.serialize());
                
                recordTransaction(account_no, "取款", amount,
                                description.empty() ? "取款" : description, "客户");
                
                json result;
                result["新余额"] = account.余额;
                result["可用余额"] = account.可用余额;
                
                return BizResult(true, result.dump(), "取款成功", 200);
            } catch (const exception& e) {
                return BizResult(false, "", "取款错误", 500);
            }
        }

        BizResult 转账(const string& from_account, const string& to_account, double amount, const string& description = "") {
            try {
                if (amount <= 0) {
                    return BizResult(false, "", "转账金额必须大于0", 400);
                }

                if (from_account == to_account) {
                    return BizResult(false, "", "不能向同一账户转账", 400);
                }

                auto from_data = _kv_more->get<string>(账户空间, from_account);
                auto to_data = _kv_more->get<string>(账户空间, to_account);
                
                if (!from_data || !to_data) {
                    return BizResult(false, "", "账户不存在", 404);
                }
                
                BankAccount from_acc = BankAccount::deserialize(*from_data);
                BankAccount to_acc = BankAccount::deserialize(*to_data);
                
                if (from_acc.状态 != "正常" || to_acc.状态 != "正常") {
                    return BizResult(false, "", "账户状态异常", 403);
                }
                
                if (from_acc.可用余额 < amount) {
                    return BizResult(false, "", "余额不足", 400);
                }
                
                // 执行转账
                from_acc.余额 -= amount;
                from_acc.可用余额 -= amount;
                to_acc.余额 += amount;
                to_acc.可用余额 += amount;
                
                _kv_more->set(账户空间, from_account, from_acc.serialize());
                _kv_more->set(账户空间, to_account, to_acc.serialize());
                
                string trans_desc = description.empty() ? "转账" : description;
                recordTransaction(from_account, "转账", amount, trans_desc, to_account);
                recordTransaction(to_account, "转账", amount, "收到转账", from_account);
                
                json result;
                result["转出账户余额"] = from_acc.余额;
                result["转入账户余额"] = to_acc.余额;
                
                return BizResult(true, result.dump(), "转账成功", 200);
            } catch (const exception& e) {
                return BizResult(false, "", "转账错误", 500);
            }
        }

        BizResult 获取交易记录(const string& account_no, int limit = 10) {
            try {
                string trans_list_key = "transactions:" + account_no;
                auto transaction_ids = _kv_more->lrange<string>(交易空间, trans_list_key, 0, limit - 1);
                
                json transactions = json::array();
                for (const auto& trans_id : transaction_ids) {
                    auto trans_data = _kv_more->get<string>(交易空间, trans_id);
                    if (trans_data) {
                        transactions.push_back(json::parse(*trans_data));
                    }
                }
                
                return BizResult(true, transactions.dump(), "交易记录获取成功", 200);
            } catch (const exception& e) {
                return BizResult(false, "", "获取交易记录错误", 500);
            }
        }

        BizResult 获取用户账户(const string& user_id) {
            try {
                auto account_no = _kv_more->get<string>(账户空间, "user:" + user_id);
                if (!account_no) {
                    return BizResult(true, "[]", "用户暂无账户", 200);
                }
                
                auto account_data = _kv_more->get<string>(账户空间, *account_no);
                if (account_data) {
                    json accounts = json::array();
                    accounts.push_back(json::parse(*account_data));
                    return BizResult(true, accounts.dump(), "用户账户获取成功", 200);
                }
                
                return BizResult(true, "[]", "用户暂无账户", 200);
            } catch (const exception& e) {
                return BizResult(false, "", "获取用户账户错误", 500);
            }
        }

        // ==================== 统计功能 ====================
        BizResult 获取统计信息() {
            try {
                json stats;
                
                // 获取总交易金额和笔数
                auto total_amount = _kv_more->get<double>(统计空间, "总交易金额");
                auto total_count = _kv_more->get<long long>(统计空间, "总交易笔数");
                
                stats["总交易金额"] = total_amount.value_or(0.0);
                stats["总交易笔数"] = total_count.value_or(0);
                
                // 获取今日统计
                string today = getCurrentTime().substr(0, 10);
                auto today_amount = _kv_more->get<double>(统计空间, "日交易总额:" + today);
                auto today_count = _kv_more->get<long long>(统计空间, "日交易笔数:" + today);
                
                stats["今日交易金额"] = today_amount.value_or(0.0);
                stats["今日交易笔数"] = today_count.value_or(0);
                
                return BizResult(true, stats.dump(), "统计信息获取成功", 200);
            } catch (const exception& e) {
                return BizResult(false, "", "获取统计信息错误", 500);
            }
        }

        // ==================== 风控和锁功能 ====================
        BizResult 添加风控数据(const string& data_type, const string& data_key, const string& risk_info) {
            try {
                bool success = _kv_more->set(风控空间, data_type + ":" + data_key, risk_info);
                return success ? 
                    BizResult(true, "", "风控数据添加成功", 200) :
                    BizResult(false, "", "风控数据添加失败", 500);
            } catch (const exception& e) {
                return BizResult(false, "", "添加风控数据错误", 500);
            }
        }

        BizResult 检查风控(const string& data_type, const string& data_key) {
            try {
                auto risk_data = _kv_more->get<string>(风控空间, data_type + ":" + data_key);
                return risk_data ? 
                    BizResult(true, *risk_data, "发现风控数据", 200) :
                    BizResult(true, "CLEAN", "无风控数据", 200);
            } catch (const exception& e) {
                return BizResult(false, "", "检查风控错误", 500);
            }
        }

        BizResult 获取锁(const string& resource, int ttl_seconds = 30) {
            try {
                string lock_value = generateId("LOCK");
                bool success = _kv_more->setnx(锁空间, resource, lock_value);
                
                if (success) {
                    _kv_more->expire(锁空间, resource, ttl_seconds);
                    return BizResult(true, lock_value, "锁获取成功", 200);
                }
                return BizResult(false, "", "锁已被占用", 409);
            } catch (const exception& e) {
                return BizResult(false, "", "获取锁错误", 500);
            }
        }

        BizResult 释放锁(const string& resource, const string& lock_value) {
            try {
                auto current_lock = _kv_more->get<string>(锁空间, resource);
                if (current_lock && *current_lock == lock_value) {
                    _kv_more->del(锁空间, resource);
                    return BizResult(true, "", "锁释放成功", 200);
                }
                return BizResult(false, "", "锁值不匹配", 409);
            } catch (const exception& e) {
                return BizResult(false, "", "释放锁错误", 500);
            }
        }

        // ==================== 命令解析和执行 ====================
        BizResult 执行命令(const string& command_line) {
            if (command_line.empty()) {
                return BizResult(false, "", "命令为空", 400);
            }
            
            auto tokens = parseCommandLine(command_line);
            string cmd = tokens[0];
            std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::toupper);
            
            // 创建会话
            if (cmd == "CREATE_SESSION" && tokens.size() >= 2) {
                return 创建会话(tokens[1]);
            }
            // 查询会话
            else if (cmd == "GET_SESSION" && tokens.size() >= 2) {
                return 获取会话(tokens[1]);
            }
            // 注册用户
            else if (cmd == "REGISTER_USER" && tokens.size() >= 5) {
                string email = tokens.size() > 5 ? tokens[5] : "";
                return 注册用户(tokens[1], tokens[2], tokens[3], tokens[4], email);
            }
            // 查用户
            else if (cmd == "GET_USER" && tokens.size() >= 2) {
                return 获取用户信息(tokens[1]);
            }
            // 开户
            else if (cmd == "CREATE_ACCOUNT" && tokens.size() >= 3) {
                double deposit = tokens.size() > 3 ? safeStod(tokens[3]) : 0.0;
                return 创建账户(tokens[1], tokens[2], deposit);
            }
            // 查余额
            else if (cmd == "GET_BALANCE" && tokens.size() >= 2) {
                return 获取账户余额(tokens[1]);
            }
            // 查整个账户对象
            else if (cmd == "GET_ACCOUNT_DETAILS" && tokens.size() >= 2) {
                return 获取账户详情(tokens[1]);
            }
            // 查某用户名下所有账户
            else if (cmd == "GET_USER_ACCOUNTS" && tokens.size() >= 2) {
                return 获取用户账户(tokens[1]);
            }
            // 存款
            else if (cmd == "DEPOSIT" && tokens.size() >= 3) {
                double amount = safeStod(tokens[2]);
                string desc = tokens.size() > 3 ? tokens[3] : "";
                return 存款(tokens[1], amount, desc);
            }
            // 取款
            else if (cmd == "WITHDRAW" && tokens.size() >= 3) {
                double amount = safeStod(tokens[2]);
                string desc = tokens.size() > 3 ? tokens[3] : "";
                return 取款(tokens[1], amount, desc);
            }
            // 转账
            else if (cmd == "TRANSFER" && tokens.size() >= 4) {
                double amount = safeStod(tokens[3]);
                string desc = tokens.size() > 4 ? tokens[4] : "";
                return 转账(tokens[1], tokens[2], amount, desc);
            }
            // 交易历史
            else if (cmd == "GET_TRANSACTIONS" && tokens.size() >= 2) {
                int limit = tokens.size() > 2 ? safeStoi(tokens[2], 10) : 10;
                return 获取交易记录(tokens[1], limit);
            }
            // 统计信息
            else if (cmd == "GET_STATS") {
                return 获取统计信息();
            }
            // 风控命令
            else if (cmd == "ADD_RISK" && tokens.size() >= 4) {
                return 添加风控数据(tokens[1], tokens[2], tokens[3]);
            }
            else if (cmd == "CHECK_RISK" && tokens.size() >= 3) {
                return 检查风控(tokens[1], tokens[2]);
            }
            // 锁命令
            else if (cmd == "ACQUIRE_LOCK" && tokens.size() >= 2) {
                return 获取锁(tokens[1]);
            }
            else if (cmd == "RELEASE_LOCK" && tokens.size() >= 3) {
                return 释放锁(tokens[1], tokens[2]);
            }
            // 系统命令
            else if (cmd == "PING") {
                return BizResult(true, "PONG", "服务正常运行", 200);
            }
            else if (cmd == "HELP" || cmd == "help") {
                string help_text = R"(
可用命令:
  用户管理:
    REGISTER_USER <用户名> <姓名> <身份证号> <手机号> [邮箱]
    GET_USER <用户ID>

  账户管理:
    CREATE_ACCOUNT <用户ID> <账户类型> [初始存款]
    GET_BALANCE <账户号>
    GET_ACCOUNT_DETAILS <账户号>
    GET_USER_ACCOUNTS <用户ID>

  交易功能:
    DEPOSIT <账户号> <金额> [描述]
    WITHDRAW <账户号> <金额> [描述]
    TRANSFER <转出账户> <转入账户> <金额> [描述]
    GET_TRANSACTIONS <账户号> [限制条数]

  统计功能:
    GET_STATS

  会话管理:
    CREATE_SESSION <用户ID>
    GET_SESSION <会话ID>

  风控管理:
    ADD_RISK <数据类型> <数据键> <风险信息>
    CHECK_RISK <数据类型> <数据键>

  锁管理:
    ACQUIRE_LOCK <资源名>
    RELEASE_LOCK <资源名> <锁值>

  系统命令:
    PING
    HELP
                )";
                return BizResult(true, help_text, "帮助信息", 200);
            }
            // 在 执行命令 方法的命令解析部分添加 CLUSTER_STATUS 命令
        else if (cmd == "CLUSTER_STATUS") {
            return 获取集群状态();
        }
            else {
                return BizResult(false, "", "未知命令: " + cmd + "，输入 HELP 查看可用命令", 400);
            }
        }
        
        // 在 Ctrl.hpp 的 MultiLevelController 类中修改获取集群状态函数
    BizResult 获取集群状态() {
        LOG(LogLevel::INFO) << "开始获取集群状态";
        
        if (!_kv_cluster) {
            LOG(LogLevel::WARNING) << "未启用集群模式";
            return BizResult(false, "", "未启用集群模式", 400);
        }
        
        try {
            LOG(LogLevel::DEBUG) << "获取集群状态信息...";
            
            // 添加超时保护
            auto future = async(launch::async, [this]() {
                try {
                    auto status = _kv_cluster->getClusterStatus();
                    auto stats = _kv_cluster->getClusterStats();
                    
                    json result;
                    result["集群状态"] = "运行中";
                    result["总节点数"] = stats.total_nodes;
                    result["在线节点数"] = stats.online_nodes;
                    result["离线节点数"] = stats.offline_nodes;
                    result["成功请求数"] = stats.successful_requests;
                    result["总请求数"] = stats.total_requests;
                    result["成功率"] = stats.success_rate;
                    result["扩展比"] = stats.estimated_scale_ratio;
                    
                    // 添加节点详情
                    json nodes_json = json::object();
                    for (const auto& [node_id, node_status] : status) {
                        string status_str;
                        switch (node_status) {
                            case Redis_Cluster_Model::NodeStatus::ONLINE:
                                status_str = "在线";
                                break;
                            case Redis_Cluster_Model::NodeStatus::OFFLINE:
                                status_str = "离线";
                                break;
                            case Redis_Cluster_Model::NodeStatus::SUSPECTED:
                                status_str = "疑似故障";
                                break;
                            case Redis_Cluster_Model::NodeStatus::RECOVERING:
                                status_str = "恢复中";
                                break;
                            default:
                                status_str = "未知";
                        }
                        nodes_json[node_id] = status_str;
                    }
                    result["节点状态"] = nodes_json;
                    
                    return BizResult(true, result.dump(), "集群状态获取成功", 200);
                    
                } catch (const exception& e) {
                    return BizResult(false, "", string("获取集群状态错误: ") + e.what(), 500);
                }
            });
            
            // 等待最多3秒
            auto status = future.wait_for(chrono::seconds(3));
            if (status == future_status::ready) {
                auto result = future.get();
                LOG(LogLevel::INFO) << "集群状态获取完成";
                return result;
            } else {
                LOG(LogLevel::ERROR) << "获取集群状态超时";
                return BizResult(false, "", "获取集群状态超时", 408);
            }
            
        } catch (const exception& e) {
            LOG(LogLevel::ERROR) << "获取集群状态异常: " << e.what();
            return BizResult(false, "", string("获取集群状态错误: ") + e.what(), 500);
        } catch (...) {
            LOG(LogLevel::ERROR) << "获取集群状态未知异常";
            return BizResult(false, "", "获取集群状态未知错误", 500);
        }
    }
};
}